#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2022/4/12 15:15
# @Author    :cjw
# 收集完测试用例，之后被调用的hook函数
import time
import logging
from typing import List

import pytest
from pytest_task2.code.calculator import Calculator
from pytest_task2.util.file_operator import YmlOperator
from pytest_task2.setting import ADD_YML_DATA_PATH, DIV_YML_DATA_PATH

# 读取yml测试文件数据
add_data = YmlOperator(ADD_YML_DATA_PATH).data
div_data = YmlOperator(DIV_YML_DATA_PATH).data


@pytest.fixture(scope="session")
def get_calc():
    """获取计算器实例"""
    logging.info("----------开始测试----------")
    logging.info("实例化calculator对象")
    yield Calculator()
    logging.info('----------结束测试----------')


@pytest.fixture()
def calc_fix():
    logging.info('----------开始计算----------')
    yield
    logging.info('----------结束计算----------')


@pytest.fixture(**add_data.get('p0'))
def get_add_p0(request):
    return request.param


@pytest.fixture(**add_data.get('p1'))
def get_add_p1(request):
    return request.param


@pytest.fixture(**add_data.get('p2'))
def get_add_p2(request):
    return request.param


@pytest.fixture(**div_data.get('p0'))
def get_div_p0(request):
    return request.param


@pytest.fixture(**div_data.get('p1'))
def get_div_p1(request):
    return request.param


@pytest.fixture(**div_data.get('p2'))
def get_div_p2(request):
    return request.param


def pytest_collection_modifyitems(
        session: "Session", config: "Config", items: List["Item"]
) -> None:
    """
    修改测试用例名称编码，执行顺序
    :param session: pytest session 对象
    :param config: 配置信息对象
    :param items: 收集到的所有测试用例对象列表，name：用例名称，nodeid：用例路径
    :return:
    """
    for item in items:
        # 修改用例名称和路径的编码
        # nodeid是用例对象的属性方法，真正改变的是用例对象的_nodeid属性
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')


@pytest.fixture(scope="session", autouse=True)
def manage_logs(request):
    """设置日志文件的文件名称"""
    now = time.strftime("%Y-%m-%d %H-%M-%S")
    log_name = 'log/' + now + '.log'

    request.config.pluginmanager.get_plugin("logging-plugin").set_log_path(log_name)
